package com.mu.securitysso.authentication;

import com.google.gson.Gson;
import com.mu.securitysso.entity.Permission;
import com.mu.securitysso.entity.Role;
import com.mu.securitysso.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * @author sht
 */
public class MyUserDetails  implements UserDetails {

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetails.class);

    Gson gson = new Gson();

    private User user;

    private List<Role> roleList ;

    private List<Permission> permissionList ;


    public MyUserDetails(User user,List<Role> roleList,List<Permission> permissionList){
        this.user = user;
        this.roleList = roleList;
        this.permissionList = permissionList;

    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        StringBuilder authoritiesBuilder = new StringBuilder("");
        List<Role> tempRoleList = this.roleList;

        if( tempRoleList != null ){
            for(Role role :tempRoleList ){
                authoritiesBuilder.append(",").append(role.getRole());
            }
        }


        List<Permission> tempPermission = this.permissionList;

        if( tempPermission != null ){
            for( Permission permission : tempPermission ){
                authoritiesBuilder.append(",").append(permission.getPermission());
            }
        }

        String authoritiesStr = "";

        if(authoritiesBuilder.length() > 0){
            authoritiesStr = authoritiesBuilder.deleteCharAt(0).toString();
        }
        logger.info("MyUserDetails getAuthorities authoritiesStr={}",authoritiesStr);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authoritiesStr);
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
